package net.hxz.commons.interceptor;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.hxz.commons.filter.AbstractExcludeUrlFilter;
import net.hxz.commons.global.Global;

/**
 * root后台拦截
 * @author LYM
 */
public class BackEndLoginInterceptor extends AbstractExcludeUrlFilter {
	private static final long serialVersionUID = 1L;

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
        	HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
        	
            if (!this.doInclude(servletRequest, servletResponse, filterChain)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }

            //对配置的excludeUrls参数包含的URL进行过滤,例如：/backEnd/;/backEnd/*;/backEnd/*.jpg
            if (this.doExclude(servletRequest, servletResponse, filterChain)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }

            response.setCharacterEncoding("UTF-8");
            if (request.getSession().getAttribute(Global.SESSION_ROOT) == null) {
                response.getWriter().print("no login");
                response.sendRedirect(((HttpServletRequest) servletRequest).getContextPath()+"/backEnd/login");
                return;
            }
            
            if(request.getRequestURI().matches("\\S*backEnd/?")){
            	response.sendRedirect(((HttpServletRequest) servletRequest).getContextPath()+"/backEnd/main");
            }
          
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            filterConfig.getServletContext().log(e.getMessage());
        }
    }
}
